package com.superhelper.app.controller;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superhelper.app.common.Consts;
import com.superhelper.app.controller.base.AbstractController;
import com.superhelper.app.domain.BuyOrder;
import com.superhelper.app.domain.PayParam;
import com.superhelper.app.domain.PayResult;
import com.superhelper.app.domain.Resp;
import com.superhelper.app.service.PayService;

/**
 * 
 */
@Controller
@RequestMapping("/v1/recharge")
public class RechargeController extends AbstractController {

    @Autowired
    private PayService payService;

    @RequestMapping("")
    @ResponseBody
    public Resp recharge(@RequestParam Long userId, @RequestParam String channel, HttpServletRequest request) {
        PayParam pp = new PayParam();
        pp.setMoney(BigDecimal.valueOf(99));// 99元
        pp.setChannel(channel);
        pp.setIp(request.getRemoteAddr());
        pp.setBody("外卖自动接单助手");
        pp.setSubject(pp.getBody());
        pp.setUid(userId + "");
        String version = request.getHeader("gzVersion");
        String device = request.getHeader("device");
        pp.setOrderFrom(device + ":" + version);
        PayResult pr = payService.pay(pp);
        return pr == null ? fail() : success(pr);
    }

    @RequestMapping("/query")
    @ResponseBody
    public Resp query(@RequestParam Long userId, @RequestParam String buyOrderCode, HttpServletRequest request) {
        BuyOrder bo = payService.queryBuyOrder(buyOrderCode);
        if (!StringUtils.equals(bo.getUid(), userId + "")) {
            return resp(Consts.Code.DATA_ERROR);
        }
        if (bo.getState() == Consts.OrderState.PAYED) {
            return resp(Consts.Code.PAY_PAYED);
        } else {
            return resp(Consts.Code.PAY_UNPAY);
        }
    }
}